<template>
  <el-upload
      class="avatar-uploader"
      :action="uploadUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-error="handleAvatarError"
      :on-progress="handleAvatarProgress"
      :http-request="customRequest"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    <!-- 上传进度条 -->
    <el-progress v-if="uploading" :percentage="uploadProgress" />
  </el-upload>
</template>

<script lang="ts" setup>
import { ref,reactive } from 'vue'
import { ElMessage, ElProgress } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

const imageUrl = ref('')
const uploading = ref(false) // 上传状态
const uploadProgress = ref(0) // 上传进度
const data = reactive({
  //uploadUrl:'https://gift-llm.oss-cn-chengdu.aliyuncs.com'
  uploadUrl:'http://localhost:8080/fastDfs/upload'
})
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  uploading.value = false
}

const handleAvatarError: UploadProps['onError'] = () => {
  ElMessage.error('Avatar upload failed!')
  uploading.value = false
}

const handleAvatarProgress: UploadProps['onProgress'] = (event, file, fileList) => {
  uploadProgress.value = Math.round((event.loaded / event.total) * 100)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isJpgOrPng = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
  if (!isJpgOrPng) {
    ElMessage.error('Avatar picture must be JPG or PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size cannot exceed 2MB!')
    return false
  }
  return true
}

// 自定义请求上传
const customRequest: UploadProps['httpRequest'] = (options) => {
  const { file, onSuccess, onError, onProgress } = options
  const formData = new FormData()
  formData.append('file', file)

  const xhr = new XMLHttpRequest()
  xhr.open('POST', options.action)

  // 上传进度
  xhr.upload.onprogress = (event) => {
    if (event.total) {
      onProgress({ percent: Math.round((event.loaded / event.total) * 100) }, file)
    }
  }

  // 请求成功
  xhr.onload = () => {
    if (xhr.status === 200) {
      onSuccess({ url: xhr.responseText }, file)
    } else {
      onError(new Error('Upload failed'))
    }
  }

  // 请求失败
  xhr.onerror = () => {
    onError(new Error('Upload failed'))
  }

  xhr.send(formData)
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
  background: #1ab394;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-progress {
  margin-top: 10px;
}
</style>
